
/**
 * 一卡通。查询
 */
function cardDoSearch(){
 	var cardNum = $('#id_cardNum').textbox('getValue');
 	if(!cardNum){
 		return;
 	}
	var param = 'cardNum='+cardNum+'';
	//query(param); 参考 "clinicDispenseSearch.js" -> doSearch() query()
}

/**
 * 查询
 */
function searchPatient(){}

/**
 * Dom Ready
 */
$(function(){
	doFirst();
	$('#tt').tabs({
		onSelect: function(	title,index ){
			if('历史记录' == title){
				historyPatientWidget.reload();
			}
		},
		onUnselect: function( title,index ){
			if('历史记录' == title){
				historyPatientWidget.clean();
			}
		}
	});
});

/**
 * 调整页签标题：这里只是对字体进行了放大处理！
 * 如果需要修改字体大小，请修改".his-title"。
 */
function adjustTabTitle(){
	var $tab_titles = $('span[class="tabs-title"]');
	$.each($tab_titles, function(i,n){
		$(n).addClass("his-title");
	});
}

/**
 * 是否显示“候诊”
 */
function whetherShowTab(){
	var pp = pageParam;
	var tabtitle = "候诊区";
	var flag = $('#tt').tabs('exists', tabtitle);
	if(flag&&pp!=null&&pp!=undefined){
		if(!!pp['ghMode']&&(pp['ghMode']=='false'||pp['ghMode']==false)){
			$('#tt').tabs('close', tabtitle);
		}
	}
}

/**
 * 初始化日期范围查询
 */
function initDateRangeSearch(){
	var now = moment().format('YYYY-MM-DD');
	$('#dd').daterangebox();
	$('#dd').daterangebox( 'setValue', now +' - '+ now );
}

/**
 * 初始化科室
 */
function initKeShiCombobox(){
	$("#id_depNum").combobox({
		url : ctx + "returnDrugSearch/queryClinicDep.do",
		valueField : 'DEP_NUM',
		textField : 'DEP_NAME',
		editable : false,
		mode : 'local',
		panelHeight : 'auto',
		filter : function(q, row) {
			q = q.toLowerCase();
			var pyjm = row['PYJM'].toLowerCase();
			return pyjm.indexOf(q) == 0;
		},
		onLoadSuccess : function() {
			var firstVal = $('#id_depNum').combobox("getData");
			if (firstVal.length > 0) {
				// 默认第一条数据
				$('#id_depNum').combobox('setValue', firstVal[0].DEP_NUM);
				$('#id_depNum').combobox('setText', firstVal[0].DEP_NAME);
			}
		}
	});
}



/**
 * domcument.Ready 后 优先执行!
 */
function doFirst(){
	adjustTabTitle();
	whetherShowTab();
	initDateRangeSearch();
	initKeShiCombobox();
	//test
	//$('#tt').tabs('select', 2);
	//historyPatientWidget.load();
}


(function($,window,document){
	var hiddenfield = '_00hidmgfield';
	/**
	 * [targerColumnArray 对象集合]
	 * [{index:1,field:'orderNum',fieldDesc:'2016001',rowspan:2}]
	 * i -> row index : 行索引. (row index start with 0)
	 * ft -> fieldText : 字段在对应行对应列的值.
	 * rs -> rowspan : 有几行需要合并.
	 * @type {Array}
	 */
	var targerColumnArray = [];
	/**
	 * [targetField 字段名称. 列名.]
	 * @type {String}
	 */
	var targetField = '';
	var temparr = [];
	/**
	 * [tempobj description]
	 * {k1:[a,b],k2:[a,b],k3:[a,b]...}
	 * @type {Object}
	 */
	var tempobj = {};
	function setarr(tca){
		targerColumnArray = tca;
	}
	function getarr(){
		return targerColumnArray;
	}
	function add(i, ft, rs){
		var obj = {};
		obj['i']  = i;
		obj['ft'] = ft;
		obj['rs'] = rs;
		targerColumnArray.push(obj);
	}
	/**
	 * [initTargetColumnArray description]
	 * @param  {[type]} data  [easyui datagrid 的数据(data)]
	 * @param  {[type]} field [需要合并的字段对象]
	 * @return {[type]}       [description]
	 */
	function initTargetColumnArray(data,field){
		var f = targetField = field;
		setarr([]);
		var rows = null;
		if(!!data && data['total']>0){
			rows = data['rows'];
		}else{
			return;
		}
		var ft = '', count = 0;
		$.each(rows, function(i, row){
			var obj = {};
			//修改rows对象，添加一个字段, 作为程序的扩展。hidden merge field.
			rows[i][hiddenfield] = rows[i][f];
			count = count + 1;
			if(i==0){
				ft = row[f];
				temparr.push( ft );
				tempobj[ft] = [count, i];
			}else{
				if(ft != row[f]){
					ft = row[f];
					count = 1; // count初始化为'1'
					temparr.push( ft );
					tempobj[ft] = [count, i];
				}else{
					tempobj[ft][0] = count;
				}
			}
		});
		$.each(temparr, function(i,n){
			add(tempobj[n][1], n, tempobj[n][0]);
		});
		temparr = [], tempobj = {};
	}
	function updateRow(me){
		$.each(targerColumnArray, function(i,n){
			if(n['rs'] > 1){
				$(me).datagrid('updateRow',{
					index: n['i'],
					row: { targetField: n['ft'] }
				});
				$(me).datagrid('mergeCells',{
					index: n['i'],
					field: targetField,
					rowspan: n['rs']
				});
			}
		});
	}
	function selectRows(me,index,row){
		$(me).datagrid('updateRow', {
			index: index,
			row: {_is_sel:'Y'}
		});
		updateRow(me);
	}
	function unSelectRows(me,index,row){
		$(me).datagrid('updateRow', {
			index: index,
			row: {_is_sel:'N'}
		});
		updateRow(me);
	}
	function clickRows(me,index,row){
		var rows = $(me).datagrid('getRows');
		$.each(rows, function(i,n){
			if(n[hiddenfield] == row[hiddenfield]){
				if('N' == row['_is_sel']){
					$(me).datagrid('unselectRow', i);
				}else{
					$(me).datagrid('selectRow', i);
				}
			}
		});
	}
	window.mergeDatagridRow = {
		init: initTargetColumnArray,
		getarr: getarr,
		updateRow: updateRow,
		selectRows: selectRows,
		unSelectRows: unSelectRows,
		clickRows: clickRows
	};
})(jQuery,window,document);

var mdr = mergeDatagridRow;

var sub_grid_data = [
	{orderNum:2016001,orderdate:'08/23/2012',shippeddate:'12/25/2012',freight:9734},
	{orderNum:2016001,orderdate:'08/24/2012',shippeddate:'12/26/2012',freight:9735},
	{orderNum:2016002,orderdate:'08/25/2012',shippeddate:'12/27/2012',freight:9736},
	{orderNum:2016003,orderdate:'08/26/2012',shippeddate:'12/28/2012',freight:9737}
];

var history_patient_conf = {
	options:{
		height:'310',
		title:'门诊患者信息',
		pageNumber : 1,
		pageSize : 10,
		pageList : [10],
		loadMsg:'数据加载中...',
		singleSelect:true,
		rownumbers:true,
		toolbar:'#tb_history_patient',
		url: ctx+'clinicRegInfo/init.do',
		columns:[[
		    /*{field:'orderNum',title:'序号',width:'3%',align:'center',
		    	formatter: function(value,row,index){return index+1;}},*/
            {field:'XH',title:'序号',width:0,hidden:'true'},
            {field:'CLINIC_REGNUM',title:'门诊登记号',width:0,hidden:'true'},
            {field:'HOSPITAL_NUM',title:'医院编号',width:0,hidden:'true'},
            {field:'DEPNUM',title:'科室编号',width:0,hidden:'true'},
            {field:'CLINICNUM',title:'门诊号',width:'9%',align:'center'},
            {field:'NAME',title:'姓名',width:'9%',align:'center'
            	,styler:function(){
            		return "font-weight:bold;";
            	}},
			{field:'SEX',title:'性别',width:'4%',align:'center'},
			{field:'AGE',title:'年龄',width:'12%',align:'center'},
			{field:'MARRIAGE',title:'婚烟',width:'5%',align:'center'},
			{field:'DEPNAME',title:'门诊科室',width:'12%',align:'center'},
			{field:'DOCTOR',title:'门诊医生',width:'9%',align:'center'},
			{field:'REGNAME',title:'登记人',width:'8%',align:'center'},
			{field:'REG_DATE',title:'登记时间',width:'12%',align:'center'}
		]],
		pagination:false
	},
	subgrid:{
		options:{
			fitColumns:true,
			rownumbers:true,
			foreignField:'CLINIC_REGNUM',
			columns:[[
				{field:'orderNum',title:'Order Number',width:200},
				{field:'orderdate',title:'Order Date',width:200},
				{field:'shippeddate',title:'Shipped Date',width:200},
				{field:'freight',title:'Freight',width:200}
			]],
			data: sub_grid_data,
			onLoadSuccess: function(data){
				var That = this;
				mdr.init(data, 'orderNum');
				mdr.updateRow( That );
			},
			onSelect: function(index,row){
				var That = this;
				mdr.selectRows(That,index,row);
			},
			onUnselect: function(index,row){
				var That = this;
				mdr.unSelectRows(That,index,row);
			},
			onClickRow: function(index,row){
				var That = this;
				mdr.clickRows(That,index,row);
			}
		}
	}
};

(function(window){
	function cleanWidget(){
		$('#id_history_parent').empty();
	}
	function addWidget(){
		$('#id_history_parent').append('<table id="history_patient_list"></table>');
	}
	function loadWidget(){
		$('#history_patient_list').datagrid({
			title:'患者信息',
			width:'100%',
			height:'100%',
			toolbar:'#tb_history_patient'
		}).datagrid('subgrid', history_patient_conf); // 'history_patient_conf'定义在外面.
	}
	function reLoadWidget(){
		cleanWidget();
		addWidget();
		loadWidget();
	}
	/**
	 * 测试时发现一个bug，如下：
	 * Uncaught TypeError: Cannot read property 'boxWidth' of null
	 * @ jquery.easyui.min.js:8913 -> var _63b=col.boxWidth+col.deltaWidth-1;
	 * 错误发生情况简述: 在`subgrid`展开后有合并行时会出现上面的错误。
	 * 目前的解决办法： 删除页面上的DOM，重新生成`datagrid`和`subgrid`。
	 */
	window.historyPatientWidget = {
		clean  : cleanWidget,
		load   : loadWidget,
		reload : reLoadWidget
	};
})(window);

